<template>
  <el-dialog
    :model-value="dialogVisible"
    :title="dialogTitle"
    width="40%"
    @close="handleClose"
  >
    <el-form :model="form" label-width="100px" :rules="rules" ref="formRef">
      <el-form-item label="汽车品牌名称" prop="name">
        <el-input v-model="form.name" />
      </el-form-item>
      <el-form-item label="汽车品牌描述" prop="des">
        <el-input type="text" v-model="form.des" />
      </el-form-item>
      <el-form-item label="品牌状态" prop="status">
        <el-radio v-model="form.status" label="1">可用</el-radio>
        <el-radio v-model="form.status" label="0">禁用</el-radio>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleConfirm">确认</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { defineEmits, ref, defineProps, watch, onMounted } from 'vue'
import { save, modify } from '../../../api/brand'
import { ElMessage } from 'element-plus'

const form = ref({
  name: '',
  des: '',
  status: ''
})

const props = defineProps({
  // 新增汽车品牌标题
  dialogTitle: {
    type: String,
    default: '',
    required: true
  },
  // 编辑行数据
  dialogRowValue: {
    type: Object,
    default: () => {}
  }
})
// 监听props.dialogRowValue值改变
watch(
  () => props.dialogRowValue,
  () => {
    // console.log(props.dialogRowValue)
    form.value = props.dialogRowValue
  },
  { deep: true, immediate: true }
)

const isDisabled = ref(false)
onMounted(() => {
  if (props.dialogTitle === '编辑') {
    isDisabled.value = true
  }
})

// 表单校验
const rules = ref({
  name: [
    { required: true, message: '汽车品牌不能为空' }
  ],
  des: [
    { required: true, message: '汽车描述不能为空' }
  ],
  status: [
    { required: true, message: '状态不能为空' }
  ]
})

const emits = defineEmits(['update:modelValue', 'query'])

// 关闭
function handleClose() {
  emits('update:modelValue', false)
}
// 确认
const formRef = ref(null)
function handleConfirm() {
  formRef.value.validate(async (valid) => {
    if (valid) {
      props.dialogTitle === '添加' ? await save(form.value) : await modify(form.value)
      ElMessage({
        message: '更新成功',
        type: 'success'
      })
      // 上层组件重新获取数据
      emits('query')
      handleClose()
    } else {
      return false
    }
  })
}
</script>

<style lang="scss" scoped>
::v-deep .el-input__prefix-inner {
  align-items: center;
}
</style>
